package org.cmy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;

import java.time.Duration;
import java.util.UUID;

@Configuration
public class OAuth2ClientConfig {

    @Bean
    public InMemoryRegisteredClientRepository clientRegistration() {
        RegisteredClient client = RegisteredClient.withId(UUID.randomUUID().toString())
                .clientId("rbac-client")
                .clientSecret("$2a$10$DdOwOxiFhDMAIbDO9c.a/u1tpFAFn9PqcPeA2Qk0Ma.D2CjW6lcIS") // 生产环境应加密
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                .redirectUri("http://127.0.0.1:8080/callback")
                .scope("read")
                .scope("write")
                .clientSettings(ClientSettings.builder().requireAuthorizationConsent(false).build())
                .tokenSettings(TokenSettings.builder()
                        .accessTokenTimeToLive(Duration.ofHours(1)) // Access Token 1小时过期
                        .refreshTokenTimeToLive(Duration.ofDays(7)) // Refresh Token 7天过期
                        .build())
                .build();

        return new InMemoryRegisteredClientRepository(client);
    }
}